package com.atguigu.gmall.mq.listener;

import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayMqConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListeners;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.sql.SQLOutput;
import java.util.Date;

/**
 * @author: Mamba
 * @version: 1.0
 * @Time: 2021/1/10 23:41
 * @Description:
 *      接收消息
 */
@Component

public class ConsumerMessage {

    //接收消息
    @RabbitListener(queues = "yaoboqueue1")
    public void receiverMessage(String msg, Channel channel, Message message){
        System.out.println("接收到的消息：" + msg);
        try {
           // int i = 10/0;
        //手动应答
        //参数1： 消息标记
        //参数2： 是否将消息放回队列   true : 放回  false : 不放回

           channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            //e.printStackTrace();
            //重新来发一次   第二次拒绝
            if (message.getMessageProperties().isRedelivered()){
                //第二次发  重新发来 、、拒绝接收
                System.out.println("拒绝接收");
                try {
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }else {
                //第一次发
                System.out.println("这是第一次发送：可以再发送一次");
                try {
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }

            }
        }
    }

    //接收延迟消息（基于死信的）
    @RabbitListeners(value = {
            @RabbitListener(queues = DeadLetterMqConfig.queue_dead_2),
            @RabbitListener(queues = DelayMqConfig.queue_delay_1)
    })
    //@RabbitListener(queues = DeadLetterMqConfig.queue_dead_2)
    public void receiverDeadLetterMessage(String msg, Channel channel,Message message) throws Exception{
        System.out.println("接收到延迟消息：" + msg);
        System.out.println("接收到的时间：" + new Date());
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),
                false);
    }
}
